const { $Message } = require('../dist/base/index');
const CryptoJS = require('crypto-js');  //引用AES源码js
const key = CryptoJS.enc.Utf8.parse("A99B88C77D66E5F4");  //十六位十六进制数作为密钥
const iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412');   //十六位十六进制数作为密钥偏移量
const app = getApp();
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

//加密方法
const Encrypt = (word) => {
  let srcs = CryptoJS.enc.Utf8.parse(word);
  let encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
  return encrypted.ciphertext.toString().toUpperCase();
}
/*
*uuid生成
*/
const wxuuid = () => {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";

  var uuid = s.join("");
  return uuid
}

/**
 * 格式化数字
 * @param {*} n 
 */
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 收藏里将自建文件夹的types进行修改
 */
const fomatForCollect = (data) => {
  const newData = [];
  data.forEach(Element => {
    if (Element.type === "collect") {
      Element.types = "cfolder"
    }
    newData.push(Element)
  })
  return newData;
}
/**
 * request方法封装
 * @param {*} method 
 * @param {*} url 
 * @param {*} data 
 * @param {*} contentType 
 * @param {*} isShow 
 */
const request = (method = 'GET', url, data, contentType = "application/json;charset=UTF-8", isShow = false, title = "加载中") => {
  return new Promise((resolve, reject) => {
    if (isShow == true)
      wx.showLoading({
        title: title,
      })
    wx.request({
      url: `${app.globalData.host}${url}`,
      method: method,
      data: method === 'GET' ? data : JSON.stringify(data),
      header: {
        'content-Type': contentType,
        'location': wx.getStorageSync('location') || "",
        'projectId': wx.getStorageSync('projectId') || "",
        "X-CSRFToken": wx.getStorageSync('csrf') || "",
        // 'cookie':"sessionid=oiz520uu7bht0u5wpodp50lnfew0ms6w",
        'cookie': "csrftoken=" + wx.getStorageSync('csrf') + ";" + wx.getStorageSync('sessionid'),
        // 'token':token,
      },
      success(res) {
        wx.hideLoading({
          success: (res) => {

          },
        })
        if (res.statusCode === 403) {
          wx.reLaunch({
            url: '/pages/index/index',
          })
        }
        if (res.statusCode === 400) {
          const showMsg = setTimeout(() => {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 1000
            })
            clearTimeout(showMsg)
          }, 250)
        }
        if (res.statusCode === 427) {
          const showMsg = setTimeout(() => {
            wx.showToast({
              title: '您没有执行该操作的权限',
              icon: 'none',
              duration: 1500
            })
            clearTimeout(showMsg)
          }, 250)

        }
        if (res.statusCode === 500) {
          wx.showToast({
            title: '服务器错误，请联系系统管理员',
            icon: 'none',
            duration: 1500
          })
        }
        resolve(res)
      },
      fail(error) {
        wx.showToast({
          title: '服务器错误，请联系系统管理员',
          icon: 'none',
          duration: 1500
        })
        // wx.hideLoading({
        //   success: (res) => {

        //   },
        // })
        reject(error)
      }
    })
  })
}
/*上传封装 */
const upRequest = (url, name, filePath, formData) => {
  return new Promise((resolve, reject) => {
    const uploadTask = wx.uploadFile({
      filePath: filePath,
      name: name,
      url: `${app.globalData.host}${url}`,
      formData: formData,
      header: {
        'Content-Type': 'multipart/form-data',
        'location': wx.getStorageSync('location') || "",
        'projectId': wx.getStorageSync('projectId') || "",
        "X-CSRFToken": wx.getStorageSync('csrf') || "",
        // 'cookie':"sessionid=oiz520uu7bht0u5wpodp50lnfew0ms6w",
        'cookie': "csrftoken=" + wx.getStorageSync('csrf') + ";" + wx.getStorageSync('sessionid'),
        // 'token':token,
      },
      success: res => {
        if (res.statusCode === 500) {
          wx.showToast({
            title: '服务器错误，请联系系统管理员',
            icon: 'none',
            duration: 1500
          })
        }
        if (res.statusCode === 427) {
          const showMsg = setTimeout(() => {
            wx.showToast({
              title: '您没有执行该操作的权限',
              icon: 'none',
              duration: 1500
            })
            clearTimeout(showMsg)
          }, 250)

        }
        resolve(res)
      },
      fail: error => {
        wx.showToast({
          title: '服务器错误，请联系系统管理员',
          icon: 'none',
          duration: 1500
        })
        // wx.hideLoading({
        //   success: (res) => {

        //   },
        // })
        reject(error)
      }
    })
    // uploadTask.onProgressUpdate((res) => {
    //   onProcess(res)
    // })
  })
}
/*函数节流*/
function throttle(fn, interval) {
  var enterTime = 0; //触发的时间
  var gapTime = interval || 300; //间隔时间，如果interval不传值，默认为300ms
  return function () {
    var that = this;
    var backTime = new Date(); //第一次函数return即触发的时间
    if (backTime - enterTime > gapTime) {
      fn.call(that, arguments);
      enterTime = backTime; //赋值给第一次触发的时间 保存第二次触发时间
    }
  };
}

/*函数防抖*/
function debounce(rightNow, fun, delay) {
  let time = null;
  return function () {
    let self = this;
    if (time) clearTimeout(time);
    rightNow.apply(self, arguments);
    time = setTimeout(() => {
      fun.apply(self, arguments);
    }, delay);
  };
}

//判断是否支持下载并预览
function canDownload(String) {
  const system = app.globalData.phoneSystem
  let type = []
  if(system.indexOf("iOS") !== -1){
   type = [
      "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf","png","jpeg"
    ]
  }else{
    type = [
      "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf","png","jpg","jpeg"
    ]
  }
  
  let isOk = false
  type.forEach(el => {
    if (el === String) {
      isOk = true
    }
  })
  return isOk
}

//判断是否支持在线编辑
function canEditor(String){
  const type = [
    'doc', 'docx', 'xls', 'xlsx', 'pptx', 'txt'
  ]
  let isOk = false
  type.forEach(el => {
    if (el === String) {
      isOk = true
    }
  })
  return isOk
}
//容量格式化大小
function formatFileSize(size) {
  if (isNaN(size)) return '-'
  if (size === 0) return "0"
  const k = 1024
  const sizes = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  const i = Math.floor(Math.log(size) / Math.log(k))

  return (size / Math.pow(k, i)).toFixed(1) + sizes[i]
}

//计算总大小
function getTotalSize(res) {
  const tempFiles = res.tempFiles
  let totalSize = 0
  tempFiles.forEach(el => {
    totalSize = totalSize + el.size
  })
  return totalSize
}

//类型转小写
function toLowerCase(String){
    return String.toLowerCase();
}
module.exports = {
  formatTime: formatTime,
  request: request,
  throttle,
  debounce,
  fomatForCollect,
  wxuuid,
  upRequest,
  canDownload,
  formatFileSize,
  getTotalSize,
  Encrypt,
  canEditor,
  toLowerCase
}
